package com.qf.utils;

import com.aliyun.oss.OSSClient;
import com.qf.properties.AliyunProterties;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class UploadUtil {


    @Resource
    private AliyunProterties aliyunProterties;

    public String uploadPic(String key,InputStream inputStream){
        OSSClient client = null;
        try {
            client = new OSSClient(aliyunProterties.getEndpoint(),aliyunProterties.getAccessKeyId(),aliyunProterties.getAccessKeySecret());

            //保存
            client.putObject(aliyunProterties.getBucketName(), key,inputStream);
            //生成时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
               date = sdf.parse(aliyunProterties.getExpire());
            } catch (ParseException e) {
                e.printStackTrace();
            }

            //获取访问路径
            URL url = client.generatePresignedUrl(aliyunProterties.getBucketName(), key, date);

            return url.toString();
        } finally {
            client.shutdown();
        }
    }

}
